package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Project.ProTalkManageMemberFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicPopupMenu;
import com.linkage.seapeak.activity.vote.CreditorMultiSelectActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 话题成员管理
 */
public class ProTalkManageMemberActivity extends BaseActivity {
    public static final String KEY_TALKID = "KEY_TALKID";
    private String mTalkId = "";
    private String mProjectID = "";

    private RadioGroup radioGroup;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private ViewPager viewPager;
    private FragmentManager fragmentManager;
    private ViewPagerAdapter adapter;
    private ArrayList<Object> items = new ArrayList<Object>();


    private PublicPopupMenu popupMenu;

    @Override
    public void initData() {
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_talk_manager_member);
        super.onCreate(savedInstanceState);
        mTalkId = getIntent().getStringExtra(KEY_TALKID);
        mProjectID = getIntent().getStringExtra(KEY_PROJECTID);

        initViews();
    }


    public void initViews() {
        titlebar_menu.setVisibility(View.VISIBLE);

        radioGroup = findViewById(R.id.radioGroup);
        radioButton1 = findViewById(R.id.radio1);
        radioButton2 = findViewById(R.id.radio2);
        viewPager = findViewById(R.id.viewpager);

        popupMenu = new PublicPopupMenu(this, "添加参与人员", "添加可浏览人员", "", "", "");
        titlebar_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupMenu.showLocation(R.id.titlebar_menu);
                popupMenu.setOnItemClickListener(new PublicPopupMenu.OnItemClickListener() {
                    @Override
                    public void onClick(PublicPopupMenu.MENUITEM item, String str) {
                        if ("0".equalsIgnoreCase(str)) {
                            Intent intent = new Intent(ProTalkManageMemberActivity.this, CreditorMultiSelectActivity.class);
                            intent.putExtra("projectId", mProjectID);
                            intent.putExtra("type", "1");
                            startActivityForResult(intent, REQUEST_SEL_JOIN_ACTIVITY);
                        } else if ("1".equalsIgnoreCase(str)) {
                            Intent intent = new Intent(ProTalkManageMemberActivity.this, CreditorMultiSelectActivity.class);
                            intent.putExtra("projectId", mProjectID);
                            intent.putExtra("type", "1");
                            startActivityForResult(intent, REQUEST_SEL_LOOK_ACTIVITY);
                        }
                    }
                });
            }
        });

        fragmentManager = this.getSupportFragmentManager();
        items.add(ProTalkManageMemberFragment.newInstance(ProTalkManageMemberFragment.TYPE_JOIN, mTalkId));
        items.add(ProTalkManageMemberFragment.newInstance(ProTalkManageMemberFragment.TYPE_BROWSE, mTalkId));

        adapter = new ViewPagerAdapter(fragmentManager, items);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0, false);
        viewPager.setOffscreenPageLimit(items.size());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio1:
                        radioButton1.setTextSize(16);
                        radioButton2.setTextSize(14);
                        viewPager.setCurrentItem(0);// 选择某一页
                        break;
                    case R.id.radio2:
                        radioButton1.setTextSize(14);
                        radioButton2.setTextSize(16);
                        viewPager.setCurrentItem(1);
                        break;
                }
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        radioButton1.setChecked(true);
                        break;
                    case 1:
                        radioButton2.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        radioButton1.performClick();
    }

    public final int REQUEST_SEL_LOOK_ACTIVITY = 10001;
    public final int REQUEST_SEL_JOIN_ACTIVITY = 10002;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        ((Fragment) items.get(viewPager.getCurrentItem())).onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case REQUEST_SEL_JOIN_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        String seluserId = intent.getStringExtra("seluserId");
                        addTalkMember(seluserId, 0);
                    }
                }
                break;
            case REQUEST_SEL_LOOK_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        String seluserId = intent.getStringExtra("seluserId");
                        addTalkMember(seluserId, 1);
                    }
                }
                break;
        }
    }


    public class ViewPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Object> items;

        public ViewPagerAdapter(FragmentManager fm, ArrayList<Object> items) {
            super(fm);
            this.items = items;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return (Fragment) items.get(position);
                case 1:
                    return (Fragment) items.get(position);
            }
            return (Fragment) items.get(position);

        }

        @Override
        public int getCount() {
            return items.size();
        }
    }


    private void addTalkMember(String members, int type) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .addTalkMember(userToken, mProjectID, mTalkId, type, members)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("添加成功");
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TALK_MEMBER);
                        EventBus.getDefault().post(event);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }


                });
    }
}